<?php
namespace Api\Service\Amazon;
use Api\Controller\Amazon\FbaStockBookController;
use Home\Service\CommonService;

class FbaStockBookService extends CommonService {
    public $accounts = array();
    public $sites = array();
    private $calDate = '';
    public $count = 0;
    public $page = 0;

    public function __construct() {
        $this->reportInventoryModel = D('Api/Amazon/ReportInventory','Model');
        $this->reportunsuppressedInventoryModel = D('Api/Amazon/ReportUnsuppressedInventory','Model');
        $this->prepareneedsService = D('Inbound/Prepareneeds', 'Service');
        $this->accounts = D('Amazon\Accounts', 'Service')->getAccounts();
        $this->sites = D('Api/Amazon/Sites', 'Service')->getSites();
        $this->calDate = M('api_fba_stock_attr',' ','fbawarehouse')->order('calDate desc')->limit(1)->getField('calDate');
    }

    public function pieceSiteData() {
        if(empty($this->calDate)) return array();
        $sql = 'SELECT
             `siteId`, SUM(`localSumQty`) AS `ls`, SUM(`workingSumQty`) AS `ws`, SUM(`shippedSumQty`) AS `ss`, SUM(`receivingSumQty`) AS `rs`, `calDate`
        FROM `api_fba_stock_attr` WHERE `calDate` = \'' . $this->calDate  . '\' AND `siteId` != \'\' GROUP BY `siteId`';

        $siteData = M('api_fba_stock_attr',' ','fbawarehouse')->query($sql);
        foreach ($siteData as &$sd) {
            $sd['siteName'] = $this->sites[$sd['siteId']];
        }

        return $siteData;
    }

    public function pieceAccountData($siteId = 0, $accountId = 0) {
        if(empty($this->calDate)) return false;
        $options = array(
            'calDate' => $this->calDate,
        );
        $siteId == 0 || $options['siteId'] = $siteId;
        $accountId == 0 || $options['accountId'] = $accountId;

        if(isset($_GET['type']) && $_GET['type'] == 'account') {
            $accountData = M('api_fba_stock_attr',' ','fbawarehouse')->where($options)->select();
        } else {
            $this->count = M('api_fba_stock_attr',' ','fbawarehouse')->where($options)->count();
            $Page            = new \Org\Util\Page($this->count, 20);// 实例化分页类 传入总记录数和每页显示的记录数(5)
            $this->page      = $Page->show();// 分页显示输出

            $accountData = M('api_fba_stock_attr',' ','fbawarehouse')->where($options)
                ->limit($Page->firstRow.','.$Page->listRows)->select();
        }

        foreach ($accountData as &$_ac) {
            $_ac['sellerName'] = $this->getSellerName($_ac['accountId']);
            $_ac['accountName'] = $this->accounts[$_ac['accountId']]['name'];
            $_ac['siteName'] = $this->sites[$_ac['siteId']];
        }

        if(!isset($_GET['type']) || $_GET['type'] != 'account') return $accountData;

        $title = array(
            'accountName' => '账号',
            'siteName' => '站点',
            'sellerName' => '销售员',
            'localSumQty' => 'FBA总实际库存',
            'workingSumQty' => '总待发货数量',
            'shippedSumQty' => '总已发货数量',
            'receivingSumQty' => '总FBA待上架库存',
            'calDate' => '最近更新时间',
        );

        $this->prepareneedsService->download_function($accountData, $title, '亚马逊账号库存汇总');

        return $accountData;
    }

    public function pieceDetailData($options = array(), $get = array()) {
        if(empty($this->calDate)) return false;
        $options += array(
            'calDate' => $this->calDate,
        );
        if(isset($get['type']) && $get['type'] == 'detail') {
            $accountData = M('api_fba_stock_data',' ','fbawarehouse')->where($options)->select();
        } else {
            $this->count = M('api_fba_stock_data',' ','fbawarehouse')->where($options)->count();
            $Page            = new \Org\Util\Page($this->count, 20);// 实例化分页类 传入总记录数和每页显示的记录数(5)
            $this->page      = $Page->show();// 分页显示输出

            $accountData = M('api_fba_stock_data',' ','fbawarehouse')->where($options)
                ->limit($Page->firstRow.','.$Page->listRows)->select();
        }

        foreach ($accountData as &$_ac) {
            $_ac['accountName'] = $this->accounts[$_ac['accountId']]['name'];
            $_ac['siteName'] = $this->sites[$_ac['siteId']];
            $_ac['sellerName'] = $this->getSellerName($_ac['accountId']);
            $_ac['totalOnWayQty'] = $_ac['workingQty'] + $_ac['shippedQty'] + $_ac['receivingQty'];
            $_ac['totalQty'] = $_ac['totalOnWayQty'] + $_ac['localQty'];
        }

        if(!isset($get['type']) || $get['type'] != 'detail') return $accountData;

        $title = array(
            'accountName' => '账号',
            'siteName' => '站点',
            'sellerName' => '销售员',
            'sellerSku' => '平台SKU',
            'asin' => 'ASIN',
            'privateSku' => '内部SKU',
            'localQty' => 'FBA实际库存',
            'workingQty' => '待发货库存',
            'shippedQty' => '已发货库存',
            'receivingQty' => '待FBA上架库存',
            'totalOnWayQty' => 'FBA在途库存（待发货库存 + 已发货库存 + 待FBA上架库存）',
            'totalQty' => '总可用库存',
            'calDate' => '最近更新时间',
        );

        $this->prepareneedsService->download_function($accountData, $title, '亚马逊账号库存明细');
    }

    private function getSellerName($accountId) {
        if(empty($accountId)) return '';
        $options = array('account_id'=>$accountId);
        $sellerIds = M('fba_account_sellers',' ','fbawarehouse')->where($options)->limit(1)->getField('seller_ids');
        $sellerIds = explode(',', $sellerIds);
        $sellerIdsLength = count($sellerIds);
        $sellerId = 0;
        for($i=0; $i < 100; $i ++) {
            if(isset($sellerIds[$sellerIdsLength - $i]) && !empty($sellerIds[$sellerIdsLength - $i])) {
                $sellerId = $sellerIds[$sellerIdsLength - $i];
                break;
            }
        }

        if(empty($sellerId))return '';

        return M('ea_admin',' ','amazonadmin')->where(array('id' => $sellerId))->getField('remark');
    }
}